package com.blobfish.kit;

import cn.hutool.core.lang.Filter;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * 翻译结果缓存工具
 * @author huangbo
 */
public class TranslatedCacheUtil {
    private static final Jedis jedis = RedisDS.create().getJedis();
    private static final String CACHE_KEY = "translateData";

    /**
     * 添加中文
     */
    public static void addChineseStr(String str) {
        if (StrUtil.isNotBlank(str) && !Validator.isGeneral(str) && !jedis.hexists(CACHE_KEY, str)) {
            jedis.hset(CACHE_KEY, str, "");
        }
    }

    /**
     * 获取结果map
     * @return
     */
    public static Map<String, String> getResultMap() {
        return MapUtil.filter(jedis.hgetAll(CACHE_KEY), new Filter<Map.Entry<String, String>>() {
            @Override
            public boolean accept(Map.Entry<String, String> stringStringEntry) {
                return StrUtil.isBlank(stringStringEntry.getValue());
            }
        });
    }

    /**
     * 存储翻译结果
     * @param key
     * @param value
     */
    public static void putResult (String key, String value) {
        if (StrUtil.isNotBlank(value) && !value.equals("null")) {
            jedis.hset(CACHE_KEY, key, value);
        }
    }

    /**
     * 获取翻译结果
     * @param key
     * @return
     */
    public static String getResult (String key) {
        if (Validator.isGeneral(key)) {
            return key;
        }
        if (!jedis.hexists(CACHE_KEY, key)) {
            addChineseStr(key);
        } else {
            String result = jedis.hget(CACHE_KEY, key);
            if (StrUtil.isNotBlank(result)) {
                return result;
            }
        }
        return "";
    }
}
